import hash from 'object-hash'

type KeyValueStore = { [key: string]: any }

export interface WidgetData {
  chartType: string | string[]
  chartOptions: KeyValueStore
  formData: KeyValueStore
  widgetJson: KeyValueStore
}

export interface Widget {
  data: WidgetData
  id: number
  name: string
  tid: number
  type: string
  chartType: string | string[]
}

interface WidgetDataQueryParams {
  id: number
  type: string
  widgetJson: KeyValueStore
}

const dfsRemoveNullyProperty = (node: any) => {
  if (!Array.isArray(node) && typeof node === 'object') {
    const result: any = {}
    Object.keys(node).forEach((key) => {
      if (node[key] !== undefined && node[key] !== null) {
        result[key] = dfsRemoveNullyProperty(node[key])
      }
    })
    return result
  }
  return node
}

export function getWidgetHash(widget: WidgetDataQueryParams) {
  const widget2 = dfsRemoveNullyProperty(widget)
  return hash(widget2, { unorderedArrays: true })
}

export function hashWidgetQuery(
  widget: WidgetDataQueryParams | { data: WidgetDataQueryParams }
) {
  if ((<{ data: WidgetDataQueryParams }>widget)?.data?.widgetJson) {
    return {
      data: {
        ...(<{ data: WidgetDataQueryParams }>widget).data,
        widgetHash: getWidgetHash(
          (<{ data: WidgetDataQueryParams }>widget).data
        ),
      },
    }
  }
  return {
    ...widget,
    widgetHash: getWidgetHash(<WidgetDataQueryParams>widget),
  }
}
